import Taro from '@tarojs/taro';
import { createAction } from 'redux-actions';
import { PRACTICE_PUT, GET_HISTORY, ET_HISTORY_DETAIL } from '../types';
import api from './api';

export const getHistoryInfo = createAction(ET_HISTORY_DETAIL, (id) => id)

let format = (data) => {
  return data;
}

export const getAllHistory = createAction(GET_HISTORY, async (category) => {
  let result = {}
  let data = {
    detail: true
  }
  let res = {
    result: {},
    payload: {}
  }
  if (category) {
    data.category = category
  }
  try {
    result = await api({
      url: '/baige/',
      method: 'GET',
      data
    })
    res = {
      result: format(result.data),
      payload: data
    }
  } catch (error) {
    console.error(error)
    res = {
      result: {},
      payload: data
    }
  }
  return res
})

export const practicePut = createAction(PRACTICE_PUT, async (data, category) => {
  let result = {};
  let req = {};
  let durationCount = 0
  let correctCount = 0;
  let errorCount = 0;
  let details = [];
  for (const item of data) {
    const { userInput, duration, y, x, isCorrect } = item;
    if (isCorrect === 'yes') {
      correctCount++
    } else {
      errorCount++
    }
    durationCount += duration
    details.push({
      op1: y,
      op2: x,
      result: userInput,
      duration
    })
  }

  req.details = details;
  // req.duration = Math.floor(durationCount * 100) / 100
  req.duration = parseInt(durationCount);
  req.correct = correctCount;
  req.error = errorCount;
  req.category = category;

  try {
    result = await api({
      url: '/baige/',
      method: 'POST',
      // method: 'GET',
      data: req
    })
    Taro.redirectTo({
      url: '/pages/summary/index'
    })
  } catch (error) {
    return result
  }
  return {
    result: result.data,
    payload: req
  }
})

export default {}
